package com.pwrd.tank;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

public class TankServer {

	public static int UUID = 1;
	
	public static final int TCP_PORT = 8888;
	
	public static final int UDP_PORT = 6666;
	
	List<Client> clients = new ArrayList<>();
	
	public void start() {

		new Thread(new UDPThread()).start();
		
		ServerSocket ss = null;
		try {
			ss = new ServerSocket(TCP_PORT);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			while(true) {
				Socket s = ss.accept();
				DataInputStream dis = new DataInputStream(s.getInputStream());
				String ip = s.getInetAddress().getHostAddress();
				int udpPort = dis.readInt();
				clients.add(new Client(ip, udpPort));
				
				DataOutputStream dos = new DataOutputStream(s.getOutputStream());
				dos.writeInt(UUID++);
				
System.out.println("A client is connect with IP adress = " + s.getInetAddress() + " and port = " + s.getPort() + "----udp port = " + udpPort);
			}
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			if(ss != null) {
				try {
					ss.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		new TankServer().start();
	}

	private class Client {
		String IP;
		int udpPort;
		
		public Client(String ip, int port) {
			IP = ip;
			udpPort = port;
		}
	}
	
	private class UDPThread implements Runnable {

		byte[] buf = new byte[1024];
		@Override
		public void run() {
			DatagramSocket ds = null;
			try {
				ds = new DatagramSocket(UDP_PORT);
			} catch (SocketException e) {
				e.printStackTrace();
			}
System.out.println("thread start at udp port = " + UDP_PORT);
			while(ds != null) {
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				try {
					// 获取从客户端发送来的udp包数据
					ds.receive(dp);
					for (int i=0; i<clients.size(); i++) {
						String IP = clients.get(i).IP;
						int port = clients.get(i).udpPort;
						//更改udp包ip和port
						dp.setSocketAddress(new InetSocketAddress(IP, port));
						//发送给其他客户端
						ds.send(dp);
					}
System.out.println("A package received");
				} catch (IOException e) {				
					e.printStackTrace();
				}
			}
		}
		
	}
}
